//
//  ProportionHStack.swift
//  xgwjinterconnection
//
//  Created by WangWeiShuo on 2025/9/2.
//
import SwiftUI
// 自定义比例布局
struct ProportionHStack: Layout {
    // 比例数组，如 [1, 2, 3] 表示 1:2:3 的比例
    let proportions: [CGFloat]
    // 子视图之间的间距
    let spacing: CGFloat
    
    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
        // 确保比例数组与子视图数量匹配
        guard proportions.count == subviews.count else {
            fatalError("Proportions count must match subviews count")
        }
        
        // 计算总比例
        let totalProportion = proportions.reduce(0, +)
        // 获取可用宽度（使用提议的宽度）
        let availableWidth = proposal.width ?? 0
        // 减去所有间距占用的宽度
        let totalSpacing = CGFloat(subviews.count - 1) * spacing
        let contentWidth = max(0, availableWidth - totalSpacing)
        
        // 计算每个子视图的宽度
        let widths = proportions.map { $0 / totalProportion * contentWidth }
        
        // 计算每个子视图的理想高度（取最高的那个）
        var maxHeight: CGFloat = 0
        for (index, subview) in subviews.enumerated() {
            let size = subview.sizeThatFits(ProposedViewSize(width: widths[index], height: nil))
            maxHeight = max(maxHeight, size.height)
        }
        
        return CGSize(width: availableWidth, height: maxHeight)
    }
    
    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
        let totalProportion = proportions.reduce(0, +)
        let availableWidth = bounds.width
        let totalSpacing = CGFloat(subviews.count - 1) * spacing
        let contentWidth = max(0, availableWidth - totalSpacing)
        let widths = proportions.map { $0 / totalProportion * contentWidth }
        
        var x = bounds.minX
        
        for (index, subview) in subviews.enumerated() {
            let width = widths[index]
            // 为每个子视图提供精确的尺寸提议
            let proposal = ProposedViewSize(width: width, height: bounds.height)
            // 放置子视图
            subview.place(
                at: CGPoint(x: x, y: bounds.minY),
                proposal: proposal
            )
            // 更新下一个子视图的 x 位置
            x += width + spacing
        }
    }
}
